package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManagerApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class FileManagerController implements FileManagerApi {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucket;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;
    @Value("${file.tokenType}")
    private String tokenType;
    @Value("${file.token.deadline}")
    private Integer deadline;
    @GetMapping("common/qnUploadToken")
    public Map<String, Object> generateUploadToken() {
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("tokenType",tokenType);
        dataMap.put("scope",bucket);
        dataMap.put("deadline",deadline);

        String fileKey= UUID.randomUUID().toString()+ RandomStringUtils.randomAlphanumeric(16);


        dataMap.put("key",fileKey);

        /*
         * postForEntity方法：
         *   1.访问的url地址（可以在此位置来指定参数）
         *   2.requestbody的数据
         *       key=value ：Map来封装
         *   3.返回结果的类型
         *       Map或自定义的类
         *   4.querystring数据
         * */
        ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, dataMap, Map.class);

        /*
         *  code、msg、result（上传凭证）
         * */
        Map body = responseEntity.getBody();



        dataMap.put("qnToken",body.get("result"));
        dataMap.put("up_region",region);
        dataMap.put("domain",domain);


        return dataMap;
    }
}
